
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';


class CountriesField extends StatefulWidget {
  @override
  State<StatefulWidget> createState() => _CountriesFieldState();
  
}

class _CountriesFieldState extends State<CountriesField> {

  final FocusNode _focusNode = FocusNode();

  OverlayEntry _overlayEntry;

  final LayerLink _layerLink = LayerLink();

  TextEditingController _editingController = TextEditingController();

  @override
  void initState() {
    // TODO: implement initState
    super.initState();
    // 添加对焦点的监听，
    // 如果获取到焦点创建一个OverlayEntry实体，插入Overlay中，
    // 如果失去焦点，移除OverlayEntry
    _focusNode.addListener(() {
      if(_focusNode.hasFocus) {
        print("field is focus");
        this._overlayEntry = this._createOverlayEnter();
        // 插入到最近的eOverlay Widget 中
        Overlay.of(context).insert(this._overlayEntry);
      } else {
        print("field not focus");
        this._overlayEntry.remove();
      }
    });
  }

  @override
  Widget build(BuildContext context) {
    return CompositedTransformTarget(
      link: this._layerLink,
      child: TextFormField(
        focusNode: _focusNode,
        controller: _editingController,
        decoration: InputDecoration(
            labelText: 'Country'
        ),
      ),
    );
  }

  OverlayEntry _createOverlayEnter() {
    // 查询 widget 的渲染框，通过这个渲染框，能够知道widget的位置、大小等渲染信息
    RenderBox renderBox = context.findRenderObject();
    // 获取 widget 的大小
    var size = renderBox.size;
    // 获取 widget 中某个点在屏幕中的坐标
    var offset = renderBox.localToGlobal(Offset.zero);
    return OverlayEntry(
      builder: (context) => Positioned(
        left: offset.dx,
        top: offset.dy + size.height + 5.0,
        width: size.width,
        child: CompositedTransformFollower(
          link: this._layerLink,
          showWhenUnlinked: false,
          offset: Offset(0,size.height + 5),
          child: Material(
            elevation: 4.0,
            child: ListView(
              padding: EdgeInsets.zero,
              shrinkWrap: true,
              children: <Widget>[
                ListTile(
                  title: Text(
                    "Syria",
                  ),
                  onTap: (){
                    print("on tap Syria");
                    _editingController.text = "Syria";
                    FocusScope.of(context).requestFocus(FocusNode());
                  },
                ),
                ListTile(
                  title: Text(
                    "Lebanon",
                  ),
                  onTap: (){
                    print("on tap Lebanon");
                    _editingController.text = "Lebanon";
                    FocusScope.of(context).requestFocus(FocusNode());
                  },
                ),
              ],
            ),
          ),
        ),
      )
    );
  }
  
}